<template>
  <div>
    <div v-if="ifSetImg" class="div-pop">
      <div class="bg-color-white pad-10 border-radius-5 width-per-90">
        <div>
          <div class="flex mar-b-10 v-align-c">
            <div v-if="nodeSrc" class="flex-item">
              <div class="flex v-align-c">
                <div class="flex-col">
                  <label>图片大小</label>
                </div>
                <div class="flex-item mar-l-10">
                  <slider @change="change" :value="nodeStyle.widthPer" block-size="20" min="10" max="100" show-value/>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="border-all pad-10">
          <div v-if="nodeSrc" class="div-img">
            <div class="align-c">
              <img @click="$pt.previewImage({urls: [nodeSrc]})" :style="'width:' + nodeStyle.width + 'rpx'"
                     :src="nodeSrc" @load="imageLoad" mode="widthFix" />
            </div>
          </div>
          <div class="flex v-align-c">
            <div class="mar-r-30">上传图片</div>
            <div class="flex-item">
              <div class="upload">
                <upload-img @upLoadSuccess="upLoadSuccess" @upLoadFail="upLoadFail" @uploadDelete="uploadDelete"
                             :showTip=false
                             :maxLength=1 :count=1></upload-img>
              </div>
            </div>
          </div>
          <div class="flex v-align-c">
            <div class="mar-r-30">说明文字</div>
            <div><input v-model="nodeText" placeholder="输入图片说明"/></div>
          </div>
          <div class="flex v-align-c mar-t-4">
            <div class="mar-r-30">
              <label>图片间距</label>
            </div>
            <div>
              <switch class="switch" @change="setIsMargin" :checked="nodeStyle.isMargin"/>
            </div>
            <div class="font-gray font-12 mar-l-10">是否保留图片上下的空白间距</div>
          </div>
        </div>
        <div class="align-c">
          <div class="flex mar-t-10">
            <button size="mini" class="mini-btn mar-r-20" @click="saveImg">确定</button>
            <button size="mini" class="mini-btn mar-l-20" @click="ifSetImg=false">取消</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import UploadImg from '@/components/UploadImg'

  export default {
    components: { UploadImg },
    data() {
      return {
        isComponents: true,
        index: 0,
        actionType: 0,
        ifSetImg: false,
        nodeSrc: '',
        nodeStyle: {
          widthPer: 100,
          width: 0,
          isMargin: true
        },
        nodeText: '',
        actualWidth: 0,
        toolAlign: false,
        files: [],
        isUploadFinish: false
      }
    },
    computed: {
      // 组装node
      getNode() {
        const node = {
          type: 'image',
          src: this.nodeSrc,
          style: this.nodeStyle,
          text: this.nodeText,
          selModule: false
        }
        return node
      }
    },
    // 监听上传是否完成
    watch: {
      isUploadFinish(val) {
        if (this.isUploadFinish) {
          this.saveImg()
        }
      }
    },
    methods: {
      // 设置图片内容
      setImg(index, actionType, node) {
        // 初始化data
        Object.assign(this.$data, this.$options.data())
        this.ifSetImg = true
        this.index = index
        this.actionType = actionType
        if (actionType === 1) {
          this.nodeSrc = node.src
          this.nodeStyle = this.$utils.deepClone(node.style)
          this.nodeText = node.text
        }
      },
      // 保存图片内容
      saveImg() {
        if (!this.isUploadFinish) {
          if (this.files.length === 0) {
            this.isUploadFinish = true
          } else {
            this.$utils.showToast({
              title: '图片上传中',
              icon: 'loading',
              duration: 150000,
              mask: true
            })
            // 开始上传文件
            this.doUpload()
          }
        } else {
          // 上传完成，清除数据
          this.files = []
          this.$pt.hideToast()
          this.ifSetImg = false
          // 保存数据
          if (this.nodeSrc) {
            // 使用深拷贝对象，防止污染
            this.$emit('saveContent', this.$utils.deepClone(this.getNode), this.index, this.actionType)
          }
        }
      },
      doUpload() {
        const that = this
        let finishCount = 0
        this.files.forEach(file => {
          // 使用微信上传（只能单张上传）
          const uploadTask = that.$pt.uploadFile({
            url: process.env.BASE_API + '/common/uploadFiles',
            filePath: file,
            name: 'files',
            success(res) {
              const result = JSON.parse(res.data)
              if (result.code === 101) {
                that.nodeSrc = result.data[0]
              } else {
                that.$utils.showToast({ title: '图片上传发生错误:' + result.msg })
                finishCount--
              }
            },
            complete() {
              finishCount++
              if (that.files.length === finishCount) {
                that.isUploadFinish = true
              }
            }
          })
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress)
          })
        })
      },
      upLoadSuccess(e) {
        this.nodeSrc = e.files[0]
        this.files = e.files
      },
      uploadDelete(e) {
        this.nodeSrc = ''
        this.nodeStyle.widthPer = 100
      },
      change(e) {
        this.nodeStyle.widthPer = e.target.value
        this.nodeStyle.width = this.actualWidth * this.nodeStyle.widthPer / 100
        if (this.nodeStyle.widthPer === 100) {
          // 如果按100%宽度显示，设置宽度为670
          this.nodeStyle.width = 670
        }
      },
      imageLoad(e) {
        this.actualWidth = e.target.width
        // 如果超过屏幕宽度750rpx，设置为屏幕宽度-80(两边留白)
        if (this.actualWidth > 670) {
          this.actualWidth = 670
        }
        this.nodeStyle.width = this.actualWidth * this.nodeStyle.widthPer / 100
        if (this.nodeStyle.widthPer === 100) {
          // 如果按100%宽度显示，设置宽度为670
          this.nodeStyle.width = 670
        }
      },
      setIsMargin(e) {
        this.nodeStyle.isMargin = e.mp.detail.value
      }
    }
  }
</script>

<style scoped>
  .tool-align {
    width: 150px;
    position: absolute;
    margin-left: 30px;
    margin-top: -79px;
    background-color: #fff;
    z-index: 999;
  }

  .div-img {
    height: 200px;
    overflow: scroll;
  }

  .upload {
    margin-top: 20px;
  }
</style>
